package com.toocms.jinjuhang.ui.mine.personal_data

import android.app.Application
import android.text.TextUtils
import androidx.databinding.ObservableField
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.StringUtils
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.toocms.jinjuhang.R
import com.toocms.jinjuhang.config.Gender
import com.toocms.jinjuhang.config.Region
import com.toocms.jinjuhang.config.Urls
import com.toocms.jinjuhang.config.UserRepository
import com.toocms.jinjuhang.data.User
import com.toocms.jinjuhang.data.system.RegionItemData
import com.toocms.jinjuhang.data.system.UploadData
import com.toocms.jinjuhang.dialog.options.OptionsDialog
import com.toocms.jinjuhang.ui.mine.bank_card.BankCardListFgt
import com.toocms.jinjuhang.ui.mine.personal_data.account.EditAccountFgt
import com.toocms.jinjuhang.widget.view_model.requestData
import com.toocms.tab.base.BaseActivity
import com.toocms.tab.base.BaseModel
import com.toocms.tab.base.BaseViewModel
import com.toocms.tab.binding.command.BindingAction
import com.toocms.tab.binding.command.BindingCommand
import com.toocms.tab.share.TabShare
import com.toocms.tab.share.listener.OnAuthListener
import com.toocms.tab.share.login.PlatformUser
import com.toocms.tab.widget.picker.OptionsPickerView
import com.toocms.tab.widget.picker.builder.OptionsPickerBuilder
import com.toocms.tab.widget.picker.builder.TimePickerBuilder
import com.umeng.socialize.bean.SHARE_MEDIA
import java.text.SimpleDateFormat
import java.util.Calendar

class PersonalDataModel(application: Application) : BaseViewModel<BaseModel>(application) {
    val dataFormat = "yyyy.MM.dd"
    val calendar by lazy {
        Calendar.getInstance()
    }
    var optionsPickerView: (OptionsPickerView<RegionItemData>)? = null
    val dataObservableField = ObservableField(User())

    val addBankCardClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        startFragment(BankCardListFgt::class.java)
    })
    val bindWechatClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        TabShare.getOneKeyLogin()
            .showUser(true, SHARE_MEDIA.WEIXIN, object : OnAuthListener() {
                override fun onComplete(
                    share_media: SHARE_MEDIA?,
                    action: Int,
                    user: PlatformUser?
                ) {

                }

                override fun onComplete(
                    share_media: SHARE_MEDIA?,
                    action: Int,
                    map: MutableMap<String, String>?
                ) {
                    super.onComplete(share_media, action, map)
                    val openid = map?.get("uid") ?: return
                    val unionid = map?.get("unionid") ?: return
                    val params = mutableMapOf<String, String?>()
                    params["member_id"] = UserRepository.user.member_id
                    params["openid"] = openid
                    params["unionid"] = unionid
                    requestData(
                        Urls.Login.SET_WECHAT,
                        params,
                        resultClass = String::class.java,
                        result = {
                            showToast(it)
                            finishFragment()
                        })
                }
            })
    })

    val headClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        startSelectSignImageAty(object : OnResultCallbackListener<LocalMedia> {
            override fun onResult(result: ArrayList<LocalMedia>?) {
                val localMedia = if (!result.isNullOrEmpty()) result[0] else null
                localMedia?.apply {
                    val imagePath = realPath
                    requestData(Urls.System.UPLOAD,
                        filePaths = mapOf(Pair("image0", imagePath)),
                        resultClass = UploadData::class.java,
                        isShowLoading = true,
                        result = {
                            it.list?.apply {
                                if (isEmpty()) return@requestData
                                val user = dataObservableField.get()
                                user?.avatar = this[0].id
                                user?.avatar_path = this[0].abs_url
                                dataObservableField.notifyChange()
                            }
                        })
                }
            }

            override fun onCancel() {

            }

        })
    })

    val accountClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        startFragment(EditAccountFgt::class.java)
    })

    val genderClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        OptionsDialog().apply {
            val items = arrayListOf(Gender.MALE, Gender.FEMALE)
            optionsItems = items
            onOptionClickListener = { option, tag ->
                title = StringUtils.getString(R.string.str_gender)
                if (option is Gender) {
                    val user = dataObservableField.get()
                    user?.gender = option.code
                    dataObservableField.notifyChange()
                }
            }
            show((ActivityUtils.getTopActivity() as BaseActivity).supportFragmentManager, null)
        }
    })

    val birthdateClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        val dataFormat = SimpleDateFormat(this@PersonalDataModel.dataFormat)
        TimePickerBuilder(
            ActivityUtils.getTopActivity()
        ) { date, v ->
            dataObservableField.get()?.apply {
                birthday = dataFormat.format(date)
                dataObservableField.notifyChange()
            }
        }.run {
            setTitleText(StringUtils.getString(R.string.str_birthdate))
            setDividerColor(0x00000000)
            setLabel("", "", "", "", "", "")
            val birthday = dataObservableField.get()?.birthday
            if (!TextUtils.isEmpty(birthday)) {
                calendar.time = dataFormat.parse(birthday)
            }
            setDate(calendar)
            build()
        }.show()
    })

    val saveClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        dataObservableField.get()?.apply {
            val params = mutableMapOf<String, String?>()
            params["member_id"] = UserRepository.user.member_id
            params["avatar"] = avatar
            params["nickname"] = nickname
            params["real_name"] = real_name
            params["mobile"] = mobile
            params["gender"] = gender
            params["birthday"] = birthday
            params["city_name"] = city_name
            requestData(Urls.Center.MODITY_INFO,
                params,
                resultClass = String::class.java,
                result = {
                    showToast(it)
                    finishFragment()
                })
        }
    })

    val nativePlaceClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        val localRegion = Region.localRegion
        if (null == localRegion) {
            showToast("正在获取地址列表,请稍后再试")
            return@BindingAction
        }
        val province = localRegion?.province ?: ArrayList()
        val city = localRegion?.city ?: ArrayList()
        val district = localRegion?.district ?: ArrayList()
        optionsPickerView = OptionsPickerBuilder(
            ActivityUtils.getTopActivity()
        ) { view, options1, options2, options3 ->
            dataObservableField.get()?.apply {
                city_name =
                    "${province[options1].region_name} ${city[options1][options2].region_name} ${district[options1][options2][options3].region_name}"
                dataObservableField.notifyChange()
            }
            optionsPickerView?.dismiss()
            return@OptionsPickerBuilder true
        }.run {
            setTitleText("籍贯")
            setDividerColor(0x00000000)
            setLabels("", "", "")
            build<RegionItemData>()
        }.apply {
            setPicker(
                province,
                city,
                district
            )
            show()
        }
    })

    override fun onResume() {
        super.onResume()
        val params = mutableMapOf<String, String?>()
        params["member_id"] = UserRepository.user.member_id
        requestData(Urls.Center.MEMBER_INFO, params, resultClass = User::class.java, result = {
            dataObservableField.set(it)
        })
    }

    init {

    }

    fun gender(code: String) = Gender.code2title(code)

}